package com.apop.hrss.home.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @author Jiayi Zheng
 * @version V1.0
 * @ClassName NotifyController
 * @date 2021/11/10 15:35
 * @Description: 接收第三方通知接口
 */
@RestController
@RequestMapping("/notify")
@Slf4j
public class NotifyController {

    // 授权码
    static final String CODE = "2c9bbe697c85140e017ca1977b8f02d12c9bbe697c85140e";

    // 个人信息请求地址(闽政通)
    @Value("${mzt.userinfo.url}")
    private String USER_INFO_URL;

    // 登陆后回调地址
    @Value("${mzt.redirect.url}")
    private String HOME_PAGE_URL;

    /**
     * 是否已经在信任系统登陆
     *
     * @param trustticket
     * @param request
     * @param response
     */
    @RequestMapping(value = "/checkStatusCallback")
    public void checkStatusCallback(@Param("loginflag") Boolean loginflag, @Param("trustticket") String trustticket, HttpServletRequest request, HttpServletResponse response, SessionStatus sessionStatus) {
        log.debug("收到checkStatusCallback loginflag {} ",loginflag);
        try {
            HttpSession session = request.getSession();
            if (loginflag) {
                // ticket 存入session 如果是集群部署则要用redis
                session.setAttribute("trustticket", trustticket);
                session.setAttribute("personalInfo", getPersonalInfo(trustticket));
                session.setAttribute("isLogin", true);

                // 跳转回首页 并且将ticket作为参数返回给客户端
                response.sendRedirect(HOME_PAGE_URL + "?loginFlag=1&checkStatus=true");

            } else {
                // session失效
                session.invalidate();
                sessionStatus.setComplete();

                // 跳转回首页 并且将ticket作为参数返回给客户端
                response.sendRedirect(HOME_PAGE_URL + "?loginFlag=0&checkStatus=true");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 接收票据 存session
     *
     * @param trustticket 票据 例如:2c9bc68b7d05e93c017d07709dd876e9
     * @return
     */
    @RequestMapping(value = "/mztLoginCallback")
    public void mztLoginCallback(@Param("trustticket") String trustticket, HttpServletRequest request, HttpServletResponse response) {
        log.debug("收到登陆回调 trustticket： {} ",trustticket);
        String personalInfo = getPersonalInfo(trustticket);
        log.debug("个人信息 {} ",personalInfo);
        HttpSession session = request.getSession();
        log.debug("sessionId {} ",session.getId());
        // ticket 存入session 如果是集群部署则要用redis
        session.setAttribute("trustticket", trustticket);
        session.setAttribute("personalInfo", personalInfo);
        session.setAttribute("isLogin", true);
        try {
            // 跳转回首页 并且将ticket作为参数返回给客户端
            response.sendRedirect(HOME_PAGE_URL + "?loginFlag=1");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 闽政通登出回调
     *
     * @param sessionStatus
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping(value = "/mztLogoutCallback")
    public void mztLogoutCallback(SessionStatus sessionStatus, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        log.debug("登出成功！");
        // session失效
        session.invalidate();
        sessionStatus.setComplete();
        try {
            // 跳转回首页 并且将ticket作为参数返回给客户端
            response.sendRedirect(HOME_PAGE_URL + "?loginFlag=0&t=1");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取个人信息
     *
     * @param ticket
     * @return
     */
    private String getPersonalInfo(String ticket) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("INVOKESERVICE_CODE", "103");
        paramsMap.put("INVOKECALLER_CODE", CODE);
        // ticket
        paramsMap.put("TRUST_TICKET", ticket);
        String POSTPARAM_JSON = JSON.toJSONString(paramsMap);
        Map<String, Object> clientParam = new HashMap<String, Object>();
        clientParam.put("POSTPARAM_JSON", POSTPARAM_JSON);
        return sendPostParams(USER_INFO_URL, clientParam);
    }

    /**
     * POST参数
     *
     * @param url
     * @param params
     * @return
     */
    private String sendPostParams(String url, Map<String, Object> params) {
        DefaultHttpClient httpclient = new DefaultHttpClient(
                new ThreadSafeClientConnManager());
        HttpPost httpost = new HttpPost(url);
        BasicResponseHandler responseHandler = new BasicResponseHandler();
        // 添加参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (params != null && params.keySet().size() > 0) {
            Iterator iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iterator.next();
                nvps.add(new BasicNameValuePair((String) entry.getKey(),
                        (String) entry.getValue()));
            }
        }
        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        try {
            String result = httpclient.execute(httpost, responseHandler).toString();
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return null;
    }
}
